﻿using cap01.Core.Annotations;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using System.Reflection;

namespace cap01.Web.Core.Extensions;

public static class SwaggerEx
{
    static Dictionary<string, string> _groups;

    static SwaggerEx()
    {
        _groups = HuaskyAPIGroup.DisplayDic();
    }

    public static void AddSwaggerDoc(this IServiceCollection services)
    {
        //这里利用了swagger的version做了分组
        services.AddSwaggerGen(c =>
        {
            foreach (var group in _groups.Keys)
            {
                c.SwaggerDoc(group, new OpenApiInfo { Title = "cap01 服务接口", Version = group });
            }

            c.DocInclusionPredicate((docName, apiDesc) =>
            {
                if (!apiDesc.TryGetMethodInfo(out MethodInfo methodInfo))
                    return false;


                if (apiDesc.GroupName == docName)
                    return true;
                else
                    return (docName == "Other") && !_groups.ContainsKey(apiDesc.GroupName ?? string.Empty);
            });

            foreach (var comment in xmlComments())
            {
                c.IncludeXmlComments(comment);
            }
        });
    }


    static string[] xmlComments()
    {
        var rootDir = AppContext.BaseDirectory;

        var output = new List<string>();

        output.AddRange(Directory.GetFiles(rootDir, "cap01.*.xml"));

        return [.. output];
    }

    public static void UseSwaggerDoc(this IApplicationBuilder app)
    {
        app.UseSwagger();
        app.UseSwaggerUI(c =>
        {
            foreach (var g in _groups)
            {
                c.SwaggerEndpoint($"/swagger/{g.Key}/swagger.json", g.Value);
            }

            c.DefaultModelsExpandDepth(-1);
        });
    }
}
